﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;

namespace System
{
    /// <summary>
    /// 枚举 辅助类
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// 获取显示Display属性（名称 | 描述）
        /// </summary>
        /// <typeparam name="TEnum">枚举类型</typeparam>
        /// <param name="enumValue">枚举常量（字符串 | 数字值）</param>
        /// <param name="isShowName">true: 显示Display属性名称；false: 显示Display属性描述</param>
        /// <returns>显示Display属性名称或描述信息</returns>
        public static string GetDisplayAttribute<TEnum>(string enumValue, bool isShowName = true)
            where TEnum : struct
        {
            TEnum outEnum;
            if (Enum.TryParse<TEnum>(enumValue, true, out outEnum))
            {
                FieldInfo outEnumFieldInfo = outEnum.GetType().GetField(outEnum.ToString());
                if (outEnumFieldInfo != null)
                {
                    DisplayAttribute displayAttribute = 
                        outEnumFieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false).Cast<DisplayAttribute>().FirstOrDefault<DisplayAttribute>();

                    if (displayAttribute != null)
                    {
                        if (isShowName)
                            return displayAttribute.Name;
                        else
                            return displayAttribute.Description;
                    }
                }
            }

            return string.Empty;
        }
    }
}
